import { _decorator, Animation } from 'cc'
import { PARAMS_NAME_ENUM } from '../Enums'
import { getInitParamsNumber, getInitParamsTrigger, StateMachine } from '../Base/StateMachine'
import { TurnLeftSubStateMachine } from './TurnLeftSubStateMachine'
import { IdleSubStateMachine } from './IdleSubStateMachine'
const { ccclass, property } = _decorator

@ccclass('PlayerStateMachine')
export class PlayerStateMachine extends StateMachine {
  initParams() {
    this.params.set(PARAMS_NAME_ENUM.IDLE, getInitParamsTrigger())
    this.params.set(PARAMS_NAME_ENUM.TURNLEFT, getInitParamsTrigger())
    this.params.set(PARAMS_NAME_ENUM.DIRECTION, getInitParamsNumber())
  }

  initStateMachines() {
    this.stateMachines.set(PARAMS_NAME_ENUM.IDLE, new IdleSubStateMachine(this))
    this.stateMachines.set(PARAMS_NAME_ENUM.TURNLEFT, new TurnLeftSubStateMachine(this))
  }

  async init() {
    this.animComp = this.addComponent(Animation)
    this.initParams()
    this.initStateMachines()
    this.initAnimationEvent()
    await Promise.all(this.waitingList)
  }

  initAnimationEvent() {
    console.log('initAnimationEvent-animComp', this.animComp)
    this.animComp.on(Animation.EventType.FINISHED, () => {
      let name = this.animComp.defaultClip.name
      const whiteList = ['turn']

      if (whiteList.some(v => name.includes(v))) {
        // 切换回动画: Idle 姿态
        this.setParams(PARAMS_NAME_ENUM.IDLE, true)
      }
    })
  }

  run() {
    console.log('run-stateMachines', this.stateMachines)
    console.log('run-currentState', this.currentState)

    switch (this.currentState) {
      case this.stateMachines.get(PARAMS_NAME_ENUM.TURNLEFT):

      case this.stateMachines.get(PARAMS_NAME_ENUM.IDLE):
        if (this.params.get(PARAMS_NAME_ENUM.TURNLEFT).value) {
          this.currentState = this.stateMachines.get(PARAMS_NAME_ENUM.TURNLEFT)
        } else if (this.params.get(PARAMS_NAME_ENUM.IDLE).value) {
          this.currentState = this.stateMachines.get(PARAMS_NAME_ENUM.IDLE)
        } else {
          this.currentState = this.currentState
        }
        break

      default:
        this.currentState = this.stateMachines.get(PARAMS_NAME_ENUM.IDLE)
    }
  }
}
